package com.scau.clothes.controller;

import com.scau.clothes.pojo.User;
import com.scau.clothes.service.UserService;
import com.scau.clothes.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@Controller
public class UserController {
    private static final String USER_ID = "userId";
    private static final String USER_NAME = "username";
    private static final String JWT_TOKEN = "JWT_TOKEN";
    @Autowired
    UserService userService;
    @RequestMapping("login")
    public ModelAndView login(HttpServletRequest request,HttpServletResponse response, String info, String password){
        ModelAndView mv = new ModelAndView();
        User user = userService.login(info, password);
        if(user==null){
            mv.setViewName("login2");
        }
        else{
            HashMap<String, String> map = new HashMap<>();
            map.put(USER_ID,user.getId()+"");
            map.put(USER_NAME,user.getUserName());
            String token = JwtUtils.createToken(map);
            //设置cookie，存放token
            Cookie cookie = new Cookie(JWT_TOKEN, token);
            cookie.setMaxAge(60*60*24);
            cookie.setPath("/");
            cookie.setDomain("localhost");
            User user1 = new User();
            user1.setId(user.getId());
            user1.setUserName(user.getUserName());
            request.setAttribute("user",user1);
            response.addCookie(cookie);
            mv.setViewName("redirect:toIndex");
        }
        return mv;
    }
    @RequestMapping("logout")
    public ModelAndView logout(HttpServletRequest request){
        ModelAndView mv = new ModelAndView();
        User user = (User) request.getAttribute("user");
        userService.logout(user.getId());
        mv.setViewName("redirect:/index");
        return mv;
    }

    @RequestMapping("register")
    public ModelAndView register(HttpServletRequest request,User user,String password2){
        ModelAndView mv = new ModelAndView();
        userService.register(user,password2);
        System.out.println(user);
        mv.setViewName("redirect:/toLogin");
        return mv;
    }
}
